<script lang="ts" setup>
import { menuModel } from '@/api/system/menu';
import { useRequest } from '@/hooks/useRequest';
import { computed, h, unref, withModifiers } from 'vue';
import { cloneDeep } from 'lodash-es';
import { NIcon, NPopconfirm, TreeOverrideNodeClickBehavior, TreeSelectRenderSuffix, useModal } from 'naive-ui';
import { AddCircle20Regular, CalendarEdit16Regular, Delete24Regular } from '@vicons/fluent';
import UpgradeForm from './components/upgradeForm.vue';

const { data, run } = useRequest(menuModel.records, {
  defaultParmas: [{ pageNum: 1, pageSize: 99999 }]
});

const treeData = computed(() => {
  const currentData = cloneDeep(unref(data)?.list) || [];
  if(!currentData.length) {return [];}
  const map = {};
  const targetData = [];
  for(const item of unref(currentData)) {
    if(!map[item.id]) {
      map[item.id] = item;
    }
    if(item.parentId === -1) {
      targetData.push(item);
    } else {
      if(map[item.parentId]) {
        if(!map[item.parentId].children) {
          map[item.parentId].children = [];
        }
        map[item.parentId].children.push(item);
      }
    }
  }
  return targetData;
});

const renderSuffix: TreeSelectRenderSuffix = ({option}) => h(
  'div',
  { class: 'flex gap-mini' },
  { default: () => [
    h(NIcon, { size: 20, onClick: withModifiers(() => createModal({parentId: option.id, parentName: option.menuName}, '新增菜单'), ['stop']) }, { default: () => [h(AddCircle20Regular)] }),
    h(NIcon, { size: 20, onClick: withModifiers(() => createModal(option, '编辑菜单'), ['stop']) }, { default: () => [h(CalendarEdit16Regular)] }),
    h('div', { onClick: withModifiers(() => '', ['stop']) }, { default: () => [
      h(NPopconfirm, { onPositiveClick: async () => {
        await menuModel.del(option.id);
        run({ pageNum: 1, pageSize: 99999 });
      } }, { default: '是否确认删除?', trigger: h(NIcon, { size: 20 }, h(Delete24Regular)) })
    ]})
  ]}
);

const override: TreeOverrideNodeClickBehavior = ({ option }) => {
  if(option.children) {
    return 'toggleExpand';
  }
  return 'default';
};

const modal = useModal();

function createModal(option, title) {
  const menuUpgradeModal = modal.create({
    title,
    preset: 'card',
    style: {
      width: '400px'
    },
    content: () => h(UpgradeForm, {
      data: option,
      onSubmit: () => {
        menuUpgradeModal.destroy();
        run({ pageNum: 1, pageSize: 99999 });
      },
      onClose: () => {
        menuUpgradeModal.destroy();
      }
    })
  });
}

</script>
<template>
  <div class="bg-white min-h-[calc(100vh-124px)] p-normal">
    <div class="flex justify-end mb-normal">
      <NButton type="primary" @click="createModal({ parentId: -1, parentName: '' }, '新增菜单')">新增</NButton>
    </div>
    <NTree
      :data="treeData"
      label-field="menuName"
      key-field="id"
      :render-suffix="renderSuffix"
      block-line
      :override-default-node-click-behavior="override"
    />
  </div>
</template>
